package com.ego.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: ego
 * @description: 公共返回对象
 * @author: KamTang
 * @create: 2022-11-11 09:37
 **/
public class Result extends HashMap<String, Object> {

    private static final long serialVersionUID = 1L;

    /**
     * 利用fastjson进行逆转
     */
    public<T> T getData(TypeReference<T> typeReference) {
        Object data = get("data");
        String s = JSON.toJSONString(data);
        return JSON.parseObject(s, typeReference);
    }

    public Result setData(Object data) {
        put("data", data);
        return this;
    }

    public Result() {
        put("code", 200);
        put("msg", "success");
    }

    public static Result error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static Result error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static Result error(int code, String msg) {
        Result r = new Result();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static Result ok(String msg) {
        Result r = new Result();
        r.put("msg", msg);
        return r;
    }

    public static Result ok(Map<String, Object> map) {
        Result r = new Result();
        r.putAll(map);
        return r;
    }

    public static Result ok() {
        return new Result();
    }

    @Override
    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public Integer getCode() {
        return (Integer) this.get("code");
    }

    public String getMsg() {
        return (String) this.get("msg");
    }


    public<T> T getData(String key, TypeReference<T> typeReference) {
        Object data = get(key);
        String s = JSON.toJSONString(data);
        return JSON.parseObject(s, typeReference);
    }
}

